package com.hroay.netty02.bio;

import lombok.extern.slf4j.Slf4j;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.util.Date;

/**
 * @author heyingcheng
 * @category Class description
 * @email heyingcheng@ctvit.com.cn
 * @date 2018/2/1 16:42
 */
@Slf4j
public class TimeServerHandler implements Runnable {

    private Socket socket;

    public TimeServerHandler(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
             BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()))){
            while (true) {
                String order = reader.readLine();
                if (order == null) {
                    break;
                }

                if ("CurrentTime".equals(order)) {
                    writer.write(new Date().toString());
                } else {
                    writer.write("Error Command");
                }
                writer.newLine();
                writer.flush();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
